<template>
  <div class="history-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-icon><Clock /></el-icon>
          <span>历史记录</span>
          <div class="header-actions">
            <el-button @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="requests.length === 0" class="empty-container">
        <el-empty description="暂无历史记录">
          <el-button type="primary" @click="$router.push('/')">
            开始新的设计
          </el-button>
        </el-empty>
      </div>

      <div v-else class="requests-list">
        <el-row :gutter="20">
          <el-col
            v-for="request in requests"
            :key="request.id"
            :span="12"
            class="request-item"
          >
            <el-card class="request-card" shadow="hover">
              <template #header>
                <div class="request-header">
                  <h3 class="request-title">{{ request.project_name }}</h3>
                  <el-tag
                    :type="getStatusType(request.status)"
                    size="small"
                  >
                    {{ getStatusText(request.status) }}
                  </el-tag>
                </div>
              </template>

              <div class="request-content">
                <div class="request-info">
                  <div class="info-item">
                    <el-icon><House /></el-icon>
                    <span>{{ request.room_type }} - {{ request.decoration_style }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Money /></el-icon>
                    <span>预算: {{ request.budget_min }}-{{ request.budget_max }}万元</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDate(request.created_at) }}</span>
                  </div>
                </div>

                <div class="request-description">
                  <p>{{ request.decoration_plan }}</p>
                </div>

                <div v-if="request.status === 'completed'" class="request-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="viewDetails(request)"
                  >
                    <el-icon><View /></el-icon>
                    查看详情
                  </el-button>
                  <el-button
                    v-if="normalizeImages(request).length"
                    type="success"
                    size="small"
                    @click="viewImages(request)"
                  >
                    <el-icon><Picture /></el-icon>
                    查看图片
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="装修方案详情"
      width="80%"
      :before-close="handleClose"
    >
      <div v-if="selectedRequest" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">
            {{ selectedRequest.project_name }}
          </el-descriptions-item>
          <el-descriptions-item label="房间类型">
            {{ selectedRequest.room_type }}
          </el-descriptions-item>
          <el-descriptions-item label="装修风格">
            {{ selectedRequest.decoration_style }}
          </el-descriptions-item>
          <el-descriptions-item label="预算范围">
            {{ selectedRequest.budget_min }}-{{ selectedRequest.budget_max }}万元
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(selectedRequest.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedRequest.status)">
              {{ getStatusText(selectedRequest.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h4>装修需求描述</h4>
          <p>{{ selectedRequest.decoration_plan }}</p>
        </div>

        <div v-if="selectedRequest.coze_response" class="detail-section">
          <h4>户型分析结果</h4>
          <div class="analysis-result" v-html="formatCozeResponse(selectedRequest.coze_response)"></div>
        </div>
      </div>
    </el-dialog>

    <!-- 图片查看对话框 -->
    <el-dialog
      v-model="imagesVisible"
      title="生成的效果图"
      width="90%"
    >
      <div v-if="selectedImages.length" class="images-grid">
        <el-row :gutter="20">
          <el-col
            v-for="(imageUrl, index) in selectedImages"
            :key="index"
            :span="12"
            class="image-item"
          >
            <el-card class="image-card" shadow="hover">
              <img
                :src="imageUrl"
                :alt="`效果图 ${index + 1}`"
                class="result-image"
                @click="previewImage(imageUrl)"
              />
              <div class="image-overlay">
                <el-button type="primary" size="small" @click="previewImage(imageUrl)">
                  <el-icon><ZoomIn /></el-icon>
                  预览
                </el-button>
                <el-button type="success" size="small" @click="downloadImage(imageUrl, index)">
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="80%">
      <div class="preview-container">
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useDecorationStore } from '@/stores/decoration'
import { Clock, Refresh, House, Money, Calendar, View, Picture, ZoomIn, Download } from '@element-plus/icons-vue'

const decorationStore = useDecorationStore()

// 响应式数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailVisible = ref(false)
const imagesVisible = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')
const selectedRequest = ref(null)
const selectedImages = ref([])

// 计算属性
const requests = computed(() => decorationStore.requests)

// 方法
const refreshData = async () => {
  await fetchRequests()
}

const fetchRequests = async () => {
  try {
    loading.value = true
    const result = await decorationStore.fetchRequests(currentPage.value, pageSize.value)
    total.value = result.total
  } catch (error) {
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRequests()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRequests()
}

const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'processing': 'primary',
    'completed': 'success',
    'failed': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '等待中',
    'processing': '处理中',
    'completed': '已完成',
    'failed': '失败'
  }
  return statusMap[status] || '未知'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const normalizeImages = (request) => {
  let images = request?.generated_images
  if (!images) return []
  try {
    if (typeof images === 'string') {
      // 可能是 JSON 字符串或逗号分隔
      const trimmed = images.trim()
      if (trimmed.startsWith('[')) {
        images = JSON.parse(trimmed)
      } else if (trimmed.includes('http')) {
        images = trimmed.split(/[,\n\s]+/).filter((s) => s.startsWith('http'))
      } else {
        images = []
      }
    }
  } catch {
    images = []
  }
  if (Array.isArray(images)) {
    return images.filter(Boolean)
  }
  return []
}

const viewDetails = (request) => {
  selectedRequest.value = request
  detailVisible.value = true
}

const viewImages = (request) => {
  selectedRequest.value = request
  selectedImages.value = normalizeImages(request)
  imagesVisible.value = true
}

const previewImage = (url) => {
  previewImageUrl.value = url
  previewVisible.value = true
}

const downloadImage = (url, index) => {
  const link = document.createElement('a')
  link.href = url
  link.download = `装修效果图_${index + 1}.jpg`
  link.click()
}

const simpleMarkdownToHtml = (text) => {
  if (!text) return ''
  let s = String(text)
  // 标题
  s = s.replace(/^###\s+(.*)$/gm, '<h4>$1</h4>')
  s = s.replace(/^##\s+(.*)$/gm, '<h3>$1</h3>')
  s = s.replace(/^#\s+(.*)$/gm, '<h2>$1</h2>')
  // 加粗
  s = s.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  // 列表项（保留为段落换行）
  s = s.replace(/^\s*[-\u2022]\s+/gm, '• ')
  // 换行
  s = s.replace(/\n/g, '<br>')
  return s
}

const formatCozeResponse = (result) => {
  // 目标：优先展示嵌套里的 data 文本（你提供的长段落）
  try {
    if (typeof result === 'string') {
      // 可能是 JSON 字符串
      try {
        const parsed = JSON.parse(result)
        // 优先 parsed.data
        if (typeof parsed?.data === 'string') {
          // data 可能再次是被转义的 JSON
          try {
            const nested = JSON.parse(parsed.data)
            const text = nested?.data || nested?.output || parsed.data
            return simpleMarkdownToHtml(text)
          } catch {
            return simpleMarkdownToHtml(parsed.data)
          }
        }
        if (parsed?.output) {
          return simpleMarkdownToHtml(parsed.output)
        }
      } catch {
        // 非 JSON，直接当作纯文本
        return simpleMarkdownToHtml(result)
      }
    }

    if (result && typeof result === 'object') {
      if (typeof result.data === 'string') {
        try {
          const nested = JSON.parse(result.data)
          const text = nested?.data || nested?.output || result.data
          return simpleMarkdownToHtml(text)
        } catch {
          return simpleMarkdownToHtml(result.data)
        }
      }
      if (result.output) {
        return simpleMarkdownToHtml(result.output)
      }
    }
  } catch {}
  return simpleMarkdownToHtml(String(result || ''))
}

const handleClose = () => {
  detailVisible.value = false
  selectedRequest.value = null
}

// 生命周期
onMounted(() => {
  fetchRequests()
})
</script>

<style scoped>
.history-container {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
}

.loading-container {
  padding: 20px;
}

.empty-container {
  padding: 40px 20px;
}

.requests-list {
  padding: 20px 0;
}

.request-item {
  margin-bottom: 20px;
}

.request-card {
  height: 100%;
}

.request-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.request-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.request-content {
  padding: 0;
}

.request-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.request-description {
  margin-bottom: 16px;
}

.request-description p {
  margin: 0;
  color: #606266;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.request-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 12px;
  color: #303133;
  font-weight: 600;
}

.detail-section p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.analysis-result {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  line-height: 1.6;
}

.images-grid {
  max-height: 60vh;
  overflow-y: auto;
}

.image-item {
  margin-bottom: 20px;
}

.image-card {
  position: relative;
  overflow: hidden;
}

.result-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.result-image:hover {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-card:hover .image-overlay {
  opacity: 1;
}

.preview-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
